package com.feeyo.groundservice.easyphotoplus.use

import android.content.Context
import android.net.Uri
import android.util.Log
import com.feeyo.groundservice.easyphotoplus.config.PictureMimeType
import com.feeyo.groundservice.easyphotoplus.engine.CompressFileEngine
import com.feeyo.groundservice.easyphotoplus.interfaces.OnKeyValueResultCallbackListener
import com.feeyo.groundservice.easyphotoplus.utils.DateUtils
import top.zibin.luban.Luban
import top.zibin.luban.OnNewCompressListener
import top.zibin.luban.OnRenameListener
import java.io.File

/**
 *作者：70893 on 2025-04-05
 *描述：
 */
class ImageFileCompressEngine : CompressFileEngine {
    override fun onStartCompress(
        context: Context,
        source: ArrayList<Uri>,
        call: OnKeyValueResultCallbackListener?
    ) {
        Luban.with(context).load(source).ignoreBy(100).setRenameListener(object : OnRenameListener {
            override fun rename(filePath: String): String {
                val indexOf: Int = filePath.lastIndexOf(".")
                val postfix = if (indexOf != -1) filePath.substring(indexOf) else ".jpg"
                return DateUtils.getCreateFileName("CMP_") + postfix
            }
        }).filter {
            if (PictureMimeType.isUrlHasImage(it) && !PictureMimeType.isHasHttp(it)) {
                true
            } else {
                !PictureMimeType.isUrlHasGif(it)
            }
        }.setCompressListener(object : OnNewCompressListener {
            override fun onStart() {

            }

            override fun onSuccess(source: String, compressFile: File) {
                Log.e("ImageFileCompressEngine", "onSuccess: $source")
                call?.onCallback(source, compressFile.absolutePath)
            }

            override fun onError(source: String, p1: Throwable) {
                call?.onCallback(source, null)
            }
        }).launch()
    }
}